import { OpenAIClient, AzureKeyCredential } from '@azure/openai'
import { OpenAIStream, StreamingTextResponse } from 'ai'

//Reference: https://sdk.vercel.ai/docs/guides/providers/openai

const client = new OpenAIClient('https://dolphin-chat.openai.azure.com/', new AzureKeyCredential(process.env.AZURE_OPENAI_API_KEY!))

export const runtime = 'edge'

export async function POST(req: Request) {
    const { messages } = await req.json()
    const response = await client.streamChatCompletions('gpt-35-turbo', messages)
    const stream = OpenAIStream(response, {
        onStart: async () => {
            // This callback is called when the stream starts
            // You can use this to save the prompt to your database
            // await savePromptToDatabase(prompt);
        },

        onToken: async (token: string) => {
            // This callback is called for each token in the stream
            // You can use this to debug the stream or save the tokens to your database
            // console.log('token: ', token)
        },

        onCompletion: async (completion: string) => {
            // This callback is called when the stream completes
            // You can use this to save the final completion to your database
            // await saveCompletionToDatabase(completion);
        }
    })
    return new StreamingTextResponse(stream)
}